#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import MySQLdb
from mod_python import util,apache
import uuid
from index import *
import global_var
import shutil

import sys
reload(sys)
sys.setdefaultencoding('utf8')

__dir__         = os.path.dirname(__file__)

def register(req):
	req.content_type = 'text/plain'
	if isinstance( req.form['reg_name'], basestring ):
		user_name = unicode(req.form['reg_name'])
	else:
		req.write(u'user_name is invalid')
		return

	if isinstance( req.form['reg_email'], basestring ):
		user_email = unicode(req.form['reg_email'])
	else:
		req.write(u'user_email is invalid')	
		return
	
	if isinstance( req.form['reg_password'], basestring ):
		user_password = unicode(req.form['reg_password'])
	else:
		req.write(u'user_password is invalid')	
		return
	value = [user_name, user_email, user_password]
	conn = MySQLdb.connect(user=global_var.mysql_user, passwd=global_var.mysql_password, host=global_var.mysql_host, port=global_var.mysql_port)
	cursor = conn.cursor()
	conn.select_db(global_var.mysql_database)
	cursor.execute("""insert into user (user_name, user_email, user_password) values(%s, %s, %s)""", value)
	cursor.close()
	util.redirect(req, '/index.py')

def auth(req):
	req.content_type = 'text/html'
	if isinstance( req.form['user_name'], basestring ):
		user_name = unicode(req.form['user_name'])
	else:
		req.write(u'user_name is invalid')
		return

	if isinstance( req.form['user_password'], basestring ):
		user_password = unicode(req.form['user_password'])
	else:
		req.write(u'user_password is invalid')	
		return

	conn = MySQLdb.connect(user=global_var.mysql_user, passwd=global_var.mysql_password, host=global_var.mysql_host, port=global_var.mysql_port)
	cursor = conn.cursor()
	conn.select_db(global_var.mysql_database)
	cursor.execute("""select user_password, user_id from user where user_name=%s""", user_name)
	row = cursor.fetchone()
	body = ''
	if row[0] == user_password :
		sess = Session.Session(req)
		sess['user_name'] = user_name
		sess['user_id'] = row[1]
		sess.save();
		user_path = os.path.join(__dir__, 'tmp/' + str(sess['user_id']))
		if not (os.path.isdir(user_path) and os.path.exists(user_path)):
			os.mkdir(user_path)
		body = index_reload(req, user_name, sess['user_id'])	
	else:
		req.write("user_name && user_password mismatch")	

	conn.close()
	return body
